/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Model.DAO;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Sixviv
 */
public abstract class AbstracDAO <T> {
    public Session session;
    public Transaction transaccion;

    public void insertar(T objecto){
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            transaccion = session.beginTransaction();
            session.save(objecto);
            transaccion.commit();
            session.close();
        }catch(Exception e){
            System.out.println(e.getMessage());
            transaccion.rollback();
            session.close();
        }
    }

    public void actualizar (T entidad){
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            transaccion = session.beginTransaction();
            session.update(entidad);
            transaccion.commit();
            session.close();
        }catch(Exception e){
            transaccion.rollback();
            session.close();
        }
    }

    public void borrar(T object){
        try{
            session = HibernateUtil.getSessionFactory().openSession();
            transaccion = session.beginTransaction();
            session.delete(object);
            transaccion.commit();
            session.close();
        }catch(Exception e){
            transaccion.rollback();
            session.close();
        }
    }
    
    public List<T> getAll(Class T){
        List<T> result = null;
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(T);
        result = criteria.list();
        session.close();
        return result;
    }

    public List<T> buscar(String condicion, Class T) {
        session = HibernateUtil.getSessionFactory().openSession();
        Criteria criteria = session.createCriteria(T);
        criteria.add(Restrictions.sqlRestriction(condicion));
        List<T> result= criteria.list();
        session.close();
        return result;
    }

}
